<template>
  <div class="pet-container">
    <!-- 查询区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="宠物ID" prop="petsId">
          <el-input
              v-model="queryParams.petsId"
              placeholder="请输入宠物ID"
              clearable
              style="width: 120px"
          />
        </el-form-item>

        <el-form-item label="宠物名称" prop="petName">
          <el-input
              v-model="queryParams.petName"
              placeholder="请输入宠物名称"
              clearable
              style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="宠物种类" prop="petKind">
          <el-select
              v-model="queryParams.petKind"
              placeholder="全部种类"
              clearable
              style="width: 120px"
          >
            <el-option label="狗" value="狗" />
            <el-option label="猫" value="猫" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fetchPets()" plain>
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery" plain>
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button @click="removePets" plain type="danger">
            <el-icon><delete /></el-icon>批量删除
          </el-button>
          <el-button @click="add" plain type="success">
            <el-icon><Refresh /></el-icon>新增宠物🐶
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
          :data="petData"
          stripe
          style="width: 100%"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
          ref="tblRef"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="petsId" label="ID" width="80" align="center" />
        <el-table-column prop="petName" label="宠物名称" width="120" />
        <el-table-column prop="petKind" label="种类" width="80" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.petKind === '狗' ? 'success' : 'warning'"
                size="small"
                effect="dark"
            >
              {{ scope.row.petKind }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="petVariety" label="品种" width="120" />
        <el-table-column prop="petSex" label="性别" width="80" align="center">
          <template #default="scope">
            <span :style="scope.row.petSex === '公' ? 'color: #409EFF' : 'color: #F56C6C'">
              {{ scope.row.petSex === '公' ? '♂' : '♀' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="petAge" label="年龄" width="80" align="center">
          <template #default="scope">
            {{ scope.row.petAge }}岁
          </template>
        </el-table-column>
        <el-table-column prop="user.name" label="主人" width="120" />
        <el-table-column prop="user.phone" label="联系电话" width="130" />
        <el-table-column label="操作"  align="center" fixed="right">
          <template #default="scope">
            <el-button type="warning" size="small" plain @click="edit(scope.row)">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--分页区-->
    <div class="el-pagination">
      <el-pagination
          v-model:current-page="PetPi.pageNo"
          v-model:page-size="PetPi.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="PetPi.total"
          @change="SearchbitPage"
      />
    </div>
    <!--添加/修改对话框-->
    <el-dialog v-model="memberDlgShow" :title="memberDlgTitle" width="600" :close-on-click-modal="false"
               @close="restMemberForm"  draggable align-center>
      <el-form label-width="100" label-position="left" :rules="rules" :model="petModel" ref="memberFormRef">
        <el-row>
          <el-col :span="16">

          </el-col>
        </el-row>
        <el-form-item label="宠物名称:" prop="petName" style="margin-top: 40px">
          <el-input v-model="petModel.petName" placeholder="请输入宠物名称"/>
        </el-form-item>

        <el-form-item label="性别:" prop="petSex" style="margin-top: 40px">
          <el-radio-group v-model="petModel.petSex">
            <el-radio label="公" value="公"/>
            <el-radio label="母" value="母"/>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="种类:" prop="petKind" style="margin-top: 40px">
          <el-radio-group v-model="petModel.petKind">
            <el-radio label="🐱" value="猫"/>
            <el-radio label="🐶 " value="狗"/>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="品种:" prop="petVariety" style="margin-top: 40px">
          <el-input v-model="petModel.petVariety" placeholder="请输入宠物品种"/>
        </el-form-item>

        <el-form-item label="宠物年龄:" prop="petAge" style="margin-top: 50px">
          <el-input v-model="petModel.petAge" placeholder="请输入宠物年龄"/>
        </el-form-item>

        <el-form-item label="您的姓名:" prop="ownerName" style="margin-top: 50px">
          <el-input v-model="petModel.ownerName" placeholder="请输入主人姓名"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="doSubmit" >确定</el-button>
          <el-button type="primary" @click="memberDlgShow=false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, toRaw, nextTick} from 'vue'
import {Search, Refresh, Delete} from '@element-plus/icons-vue'
import api from '@/util/api.js'
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";


let memberDlgShow = ref(false);

let memberDlgTitle = ref();

//新增表单对象
let memberFormRef = ref();

let petModel = ref({
  petName:null,
  petSex:"公",
  petKind:"狗",
  petAge:null,
  petVariety:null,
  ownerName:null
});

const rules = {
  petName:[{
    required:true,
    message:"宝宝你的宠物姓名不要忘记填哦",
    trigger:"blur"
  }],
  petAge:[{
    required:true,
    message:"您的宠物年龄不要忘记填哦"
  }],
  petVariety:[{
    required:true,
    message:"请您填写您的宠物品种",
    trigger: "blur"
  }],
  ownerName:[{
    required:true,
    message:"请您填写您的姓名",
    trigger: "blur"
  }]
}

let mode = "add";

function add(){
  memberDlgShow.value = true;
  memberDlgTitle.value = "新增宠物QAQ";
  mode = "add";
}


function edit(row){
  if (!row || !row.petsId) {
    ElMessage.error("请选择有效的客户数据");
    return;
  }

  memberDlgShow.value = true;
  mode = "edit";
  memberDlgTitle.value = "修改宠物信息";

  //数据回显
  nextTick(() => {
    // 注意字段名称要与后端返回的数据一致
    petModel.value = cloneDeep({
      petsId:row.petsId,
      petName:row.petName,
      petSex:row.petSex,
      petKind:row.petKind,
      petAge:row.petAge,
      petVariety:row.petVariety,
      ownerName:row.user.name
    });
  });
}

function doSubmit(){
  if (mode === "add"){
    addSubmit();
  }else {
    editSubmit();
  }
}

async function addSubmit(){
  let params = toRaw(petModel.value);
  let resp = await api ({
    url:"/pets",
    method:"post",
    data:params
  });

  if (resp.success){
    let newPet = resp.data;

    petData.value.push(newPet);

    memberDlgShow.value = false;
    await fetchPets();
    ElMessage.success("添加宠物成功");
  }else {
    ElMessage.error("添加宠物失败,请检查用户是否存在");
  }
}

// 修改提交函数
async function editSubmit() {
  try {
    let params = toRaw(petModel.value);
    let resp = await api({
      url: "/pets", // 假设使用RESTful风格API
      method: "put",
      data: params
    });
    console.log(resp)
    if (resp.success) {
      memberDlgShow.value = false;
      await fetchPets(PetPi.pageNo, PetPi.pageSize); // 保持当前分页
      ElMessage.success("修改宠物信息成功");
    } else {
      ElMessage.error(resp.msg || "修改宠物信息失败");
    }
  } catch (error) {
    ElMessage.error("修改宠物信息时发生错误");
    console.error(error);
  }
}

//重置会员表单
function restMemberForm(){
  memberFormRef.value.resetFields();
}


// 查询参数
const queryParams = reactive({
  petsId: '',
  petName: '',
  petKind: ''
})

let PetPi = reactive({
  pageNo:1,
  pageSize:20,
  total:0
})

// 宠物数据
const petData = ref([])

let queryForm = ref();
// 获取宠物数据
async function fetchPets(pageNo=1,pageSize=20){
  let params = toRaw(queryParams)
  let resp =await api({
    url:"/pets",
    method:"get",
    params:{
      pageNo,
      pageSize,
      ...params
    }
  });

  if (resp.success){
    petData.value = resp.data.records;
    PetPi.pageNo = resp.data.current;
    PetPi.pageSize = resp.data.size;
    PetPi.total = resp.data.total;
  }else {
    ElMessage.error("出现未知错误");
  }

}
// 处理查询
// const handleSearch = (pageNo,pageSize) => {
//   fetchPets(pageNo,pageSize)
// }

// 重置查询
// const resetQuery = () => {
//   Object.keys(queryParams).forEach(key => {
//     queryParams[key] = ''
//   })
//   fetchPets()
// }

function resetQuery() {
  queryForm.value.resetFields();
  fetchPets();
}



function SearchbitPage(pageNo,pageSize){
  fetchPets(pageNo,pageSize);
}

let tblRef = ref();


function removePets(){
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0){
    ElMessage.warning("请选中您要删除的行");
  }else {
    ElMessageBox.confirm("是否确认删除要选中的行?","警告",{
      confirmButtonText:"确定",
      cancelButtonText:"取消",
      type:"warning"
    }).then(()=>{
      let ids = rows.map(it=>it.petsId);
      removeById(ids);
      fetchPets();
    }).catch(()=>{
    });
  }
}
//批量删除会员，参数为会员数组
async function removeById(ids){
  let resp = await api({
    url:"/pets",
    method:"delete",
    data:ids
  });
  if (resp.success){
    ElMessage.success("删除成功，共删除"+resp.data+"条");
  }else {
    ElMessage.error("删除失败,请稍后再试或联系管理员");
  }
}

// 组件挂载时加载数据
onMounted(() => {
  fetchPets()
})
</script>

<style scoped>
.pet-container {
  padding: 15px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-card {
  margin-bottom: 15px;
  border: none;
  border-bottom: 1px solid #ebeef5;
  border-radius: 4px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 4px;
  overflow: hidden;
}

.el-card :deep(.el-card__body) {
  padding: 15px;
}

.el-table {
  flex: 1;
}

.el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>